"use strict"
//配置文件，postRouter
var router = "http://121.46.130.92:8000";
var host = "../"; //主站地址
var imgRoot = host + "images"; //图片根目录
var imgRootDeep = "../" + host + "images"; //三层图片目录

//控件集合类
var Controller = {};
//表单引擎，数据绑定。
var Data = {};
//cookie
var Cookie = {};
//信息提示框
var Message = {};
//继承参数，并校验参数
//传参，接收对象，传入对象
Controller.extend = function (conObj, parameter) {
    for (var key in parameter) {
        conObj[key] = parameter[key];
    }
    //参数校验
    for (var key in conObj) {
        if (typeof (conObj[key]) != "function" && !conObj[key]) {
            console.warn("Parameter " + key + " correspondence value does not exist");
        }
    }
}
//带px的值转数字
Controller.pxToFloat = function (str) {
    if (typeof (str) == "string") {
        return parseFloat(str.replace("px", ""));
    } else {
        return 0;
    }
}
//标签页
Controller.TabControl = function (parameter) {
    var result = {
        container: null,
        tabNavItem: null,
        tabConItem: null,
        tagName: null,
        event: null,
        activeClass: "shop-active"
    };
    result.init = function (parameter) {
        //接收传参
        Controller.extend(this, parameter);
        //添加事件
        this.addEvent(this);
    };
    result.addEvent = function (curObj) {
        var curobj = curObj;
        var father;
        if (typeof (curobj.container) == "string") {
            father = $(curobj.container);
        } else {
            father = curobj.container;
        }
        var navList = father.find(curobj.tabNavItem);
        var conList = father.find(curobj.tabConItem);

        if (this.event == "hover") {
            //hover事件监听方法
            $(navList).off("mouseover").on("mouseover", function () {

                var tag = $(this).attr(thcurobjis.tagName) || $(this).prop(curobj.tagName);
                //移除active
                var tag = $(this).attr(curobj.tagName) || $(this).prop(curobj.tagName);
                //移除active
                navList.removeClass(curObj.activeClass);
                conList.removeClass(curObj.activeClass);
                father.find(curobj.tabNavItem + "[" + curobj.tagName + "=" + tag + "]").addClass(curObj.activeClass);
                father.find(curobj.tabConItem + "[" + curobj.tagName + "=" + tag + "]").addClass(curObj.activeClass);
            });
        } else {
            //其它事件，通用方法
            $(navList).off(curobj.event).on(curobj.event, function () {
                var tag = $(this).attr(curobj.tagName) || $(this).prop(curobj.tagName);
                //移除active
                navList.removeClass(curObj.activeClass);
                conList.removeClass(curObj.activeClass);
                father.find(curobj.tabNavItem + "[" + curobj.tagName + "=" + tag + "]").addClass(curObj.activeClass);
                father.find(curobj.tabConItem + "[" + curobj.tagName + "=" + tag + "]").addClass(curObj.activeClass);
            });
        }
    }
    result.init(parameter);
    return result;
}
/*
 *搜索控件（ps:目前只单条件）
 *调用方式如下
 * var page = new PageControl();
 * page.init({
 *         totalCount:15,    //总页数
 *         conter:".app",    //容器选择器
 *         nowPage:1,        //当前页，默认第几页
 *         url:"localhost:5331", //接口请求api
 *         data:{                //api传参，未接入扩展参数
 *             text:11
 *         }
 *     });
 */

Controller.Search = function () {
    var result = {
        keyList: null,
        conter: 'body',
        parameter: null,
        callback: null,
        init: function (obj) {
            //初始化
            this.contact(obj);
            this.renderTemplate();
        },
        contact: function (obj) {
            for (var key in obj) {
                this[key] = obj[key];
            }
        },
        addEvent: function () {
            var self = this;
            $(this.conter).find('.Controller-search-btn').off('click').on('click', function () {
                var para = self.getParameter();
                if (para == null) {
                    alert("请选择要搜索的字段！");
                    return;
                }
                self.parameter = para;
                //进行搜索，调用回掉
                typeof (self.callback) == "function" && self.callback(para);
            });
            //回车事件
            $(this.conter).find('[name=ControllerSearchingValue]').off('keydown').on('keydown', function (e) {
                if (e.keyCode == 13) {
                    var para = self.getParameter();
                    if (para == null) {
                        alert("请选择要搜索的字段！");
                        return;
                    }
                    self.parameter = para;
                    //进行搜索，调用回掉
                    typeof (self.callback) == "function" && self.callback(para);
                }
            });
        },
        renderTemplate: function () {
            //模板渲染
            $(this.conter).html('');
            _html = '';
            _html += '<div class="Controller-single-search">\
          <select name="ControllerSearchingKey" class="Controller-search-select" id="">\
          <option value="-1">请选择</option>';
            //添加选择字段
            for (var key in this.keyList) {
                _html += '<option value="' + this.keyList[key].enName + '">' + this.keyList[key].cnName + '</option>';
            }
            _html += '</select>\
                        <input name="ControllerSearchingValue" placeholder="请输入" class="Controller-search-input" />\
                        <a class="Controller-search-btn Controller-btn Controller-btn-green">搜索</a>\
                        <div class="clear"></div>\
                    </div>';
            $(this.conter).append(_html);
            this.addEvent();
        },
        getParameter: function () {
            var result = {};
            var keys = $(this.conter).find('select').val();
            var val = $(this.conter).find('input').val();
            //如果没有选择，提示不进行搜索；
            if (keys == '-1') {
                return null;
            }
            result['key'] = keys;
            result['value'] = val;
            result[keys] = val;
            return result;
        }
    };
    return result;
};
//左右切换滚动
Controller.Slider = function (parameter) {
    var result = {
        father: null,
        container: null,
        prevBtn: null,
        nextBtn: null,
        speed: 400,
        delay: 3000,
        offSet: "auto", //自动单元滚动
        itemSelector: null,
        fatherSize: "auto",
        //autoPlay: true, //自动滚动，后期扩展
        orientation: "horizontal", //滚动方向，后期扩展
    };
    result.init = function (parameter) {
        Controller.extend(this, parameter);
        this.addEvent(this);
    }
    result.addEvent = function (obj) {
        var curObj = obj;
        //父容器,父容器宽度,上页按钮，下页按钮，元单位，偏移位置，速度,总历时,容器,容器宽度,容器高度，偏移量阈值，计量标准单元格
        var father, fatherSize, prevBtn, nextBtn, itemCon, offsetWidth, speed, delay, container, conWidth, conHeight, offKey, unitItem;
        if (typeof (curObj.container) == "string") {
            father = $(curObj.father);
        } else {
            father = curObj.container;
        }
        prevBtn = father.find(curObj.prevBtn);
        nextBtn = father.find(curObj.nextBtn);
        container = father.find(curObj.container);
        speed = curObj.speed;
        itemCon = container.find(curObj.itemSelector);
        delay = curObj.delay;

        // 标准计算单元格
        if (itemCon.length > 0 && itemCon.css("margin-right") && itemCon.css("margin-left")) {
            unitItem = itemCon.eq(1);
            if (!unitItem) {
                unitItem = itemCon.eq(0);
            }
        } else {
            unitItem = itemCon;
        }
        //计算内外边距
        var itemMH = Controller.pxToFloat(unitItem.css("margin-left")) + Controller.pxToFloat(unitItem.css("margin-right"));
        var itemPH = Controller.pxToFloat(unitItem.css("padding-left")) + Controller.pxToFloat(unitItem.css("padding-left"));
        var itemMV = Controller.pxToFloat(unitItem.css("margin-bottom")) + Controller.pxToFloat(unitItem.css("margin-top"));
        var itemPV = Controller.pxToFloat(unitItem.css("padding-bottom")) + Controller.pxToFloat(unitItem.css("padding-top"));
        //计算单元宽高
        var itemW = unitItem.width() + itemPH + itemMH;
        var itemH = unitItem.width() + itemPV + itemMV;
        //计算容器宽高
        conWidth = itemW * itemCon.length;
        conHeight = itemH * itemCon.length;
        //取父容器宽度
        if (curObj.fatherSize == "auto") {
            if (curObj.orientation == "horizontal") {
                fatherSize = father.width();
            } else {
                fatherSize = father.height();
            }
        } else {
            fatherSize = curObj.fatherSize;
        }
        //设置容器高
        container.width(conWidth);
        //获取偏移量
        if (curObj.offSet == "auto") {
            if (curObj.orientation == "horizontal") {
                //计算单元格宽度，自动设为偏移,宽高+内外边距
                offsetWidth = itemW;
                offKey = conWidth - this.fatherSize - itemMH
            } else {
                offsetWidth = itemH;
                offKey = conHeight - this.fatherSize - itemMV;
            }
        } else {
            //如果自定义了偏移量，直接继承
            offsetWidth = curObj.offSet;
        }
        //按钮初始化显示隐藏
        if (conWidth <= fatherSize) {
            prevBtn.hide();
            nextBtn.hide();
        }
        //添加事件绑定
        prevBtn.off("click").on("click", function (e) {
            // 上一页
            var mof = Controller.pxToFloat(container.css("margin-left"));
            var newof = mof + offsetWidth;
            //如果不超过一屏，则不实现滚动
            if (conWidth <= fatherSize) {
                return;
            }
            if (newof >= 0) {
                prevBtn.hide();
                container.stop(false, true).animate({
                    "margin-left": "0px"
                }, speed);
            } else {
                nextBtn.show();
                container.stop(false, true).animate({
                    "margin-left": newof + "px"
                }, speed);
            }
        });
        nextBtn.off("click").on("click", function (e) {
            //下一页
            var mof = Controller.pxToFloat(container.css("marginLeft"));
            var newof = mof - offsetWidth;
            //如果不超过一屏，则不实现滚动
            if (conWidth <= fatherSize) {
                return;
            }
            //取第一个放到最后一个
            if (newof <= -offKey) {
                nextBtn.hide();
                container.stop(false, false).animate({
                    "marginLeft": -offKey + "px"
                }, speed);
            } else {
                prevBtn.show();
                container.stop(false, false).animate({
                    "marginLeft": newof + "px"
                }, speed);
            }
        });
    };
    result.init(parameter);
    return result;
}
/*
 *翻页控件封装
 *调用方式如下
 * var page = new Controller.PageControl();
 * page.init({
 *         totalCount:15,    //总页数
 *         conter:".app",    //容器选择器
 *         nowPage:1,        //当前页，默认第几页
 *         gotoCallBack:fun,
 *         callback:fun
 *     });
 */

Controller.PageControl = function () {
    //实例化对象，可以多次引用
    var result = {
        conter: "body",
        totalCount: 0,
        activeClass: "shop-active",
        nowPage: 1,
        callback: null,
        gotoCallBack: null,
        init: function (obj) {
            var obj = obj ? obj : {};
            //接受传参
            this.conact(obj);
            //初始化控件
            this.renderTemplate();
        },
        conact: function (obj) {
            for (var key in obj) {
                this[key] = obj[key];
            }
        },
        renderTemplate: function (remberVal) {
            //清空所有
            $(this.conter).children().remove();
            var _html = '';
            /*<li data-num="-3">首页</li>*/
            _html += '<ul class="Controller-page-list">';
            if (this.nowPage == 1) {
                _html += '<li data-num="-1" class="shop-disable">&lt;</li>';
            } else {
                _html += '<li data-num="-1">&lt;</li>';
            }
            if (this.totalCount <= 6) {
                for (var i = 1; i <= this.totalCount; i++) {
                    _html += '<li data-num="' + i + '">' + i + '</li>';
                }
            } else {
                if (this.nowPage <= 3) {
                    for (var i = 1; i <= this.totalCount; i++) {
                        if (i <= 5) {
                            _html += '<li data-num="' + i + '">' + i + '</li>';
                        } else {
                            _html += '<span class="Controller-page-omit">···</span>';
                            _html += '<li data-num="' + this.totalCount + '">' + this.totalCount + '</li>';
                            break;
                        }
                    }
                } else if (this.nowPage >= (this.totalCount - 3)) {
                    for (var i = (this.totalCount - 5); i <= this.totalCount; i++) {
                        _html += '<li data-num="' + i + '">' + i + '</li>';
                    }
                } else {
                    for (var i = this.nowPage - 2; i <= this.totalCount; i++) {
                        if (i <= this.nowPage + 2) {
                            _html += '<li data-num="' + i + '">' + i + '</li>';
                        } else {
                            _html += '<span class="Controller-page-omit">···</span>';
                            _html += '<li data-num="' + this.totalCount + '">' + this.totalCount + '</li>';
                            break;
                        }
                    }
                }
            }
            if (this.nowPage == this.totalCount) {
                _html += '<li data-num="-2" class="shop-disable">&gt;</li>';
            } else {
                _html += '<li data-num="-2">&gt;</li>';
            }
            _html += '<span class="Controller-page-omit">共' + this.totalCount + '页，到第</span>';
            if (remberVal) {
                _html += '<input data-pageindex-max="10" type="text" value="' + this.nowPage + '" class="shop-input">';
            } else {
                _html += '<input data-pageindex-max="10" type="text" class="shop-input">';
            }
            _html += '<span class="Controller-page-omit">页</span>\
                <div class="shop-sure-btn">确定</div>';
            _html += '</ul>';
            $(this.conter).append(_html);
            this.addEvent(); //动态生成标签，需重绑demo树的事件
            this.showLight();
        },
        showLight: function () {
            //显示对应的标签
            $(this.conter).find('li').removeClass(this.activeClass);
            $(this.conter).find('li[data-num=' + this.nowPage + ']').addClass(this.activeClass);
        },
        addEvent: function () {
            var self = this;
            //单击跳转
            $(this.conter).find('li:not(".shop-disable")').off('click').on('click', function () {
                var _cur = $(this);
                var pagenum = parseInt(_cur.attr("data-num"));
                switch (pagenum) {
                    case -4:
                        self.lastPage();
                        break;
                    case -3:
                        self.firstPage();
                        break;
                    case -2:
                        self.nextPage();
                        break;
                    case -1:
                        self.prePage();
                        break;
                    default:
                        self.nowPage = pagenum;
                        self.goTo();
                        break;
                };
            });
            //跳页按钮
            $(this.conter).find(".shop-sure-btn").off("click").on("click", function () {
                //取出同级元素的页码
                var inputNum = $(this).siblings(".shop-input").val() | 0;
                self.goPage(inputNum);
            });
            //监听页码输入，禁止输入非数字
            $(this.conter).find(".shop-input").on("input propertychange", function (e) {
                var _val = $(this).val();
                $(this).val(Controller.getNum(_val));
            });
        },
        goPage: function (pages) {
            if (pages > this.totalCount) {
                alert("页码超出页码总数");
                return;
            } else if (pages <= 0) {
                alert("页面不能为0或负数");
            } else {
                this.nowPage = pages;
                this.renderTemplate(true);
                typeof (this.gotoCallBack) == "function" && this.gotoCallBack(this.nowPage);
            }
        },
        nextPage: function () {
            //下一页
            if (this.nowPage == this.totalCount) {
                //alert("已是最后一页");

                return;
            } else {
                this.nowPage++;
                //调用查询数据接口
                this.renderTemplate();
                typeof (this.callback) == "function" && this.callback(this.nowPage);
            }
        },
        prePage: function () {
            if (this.nowPage == 1) {
                //alert("已是第一页");
            } else {
                this.nowPage--;
                //调用查询数据接口
                this.renderTemplate();
                typeof (this.callback) == "function" && this.callback(this.nowPage);
            }
        },
        firstPage: function () {
            this.nowPage = 1;
            //调用查询数据接口
            this.renderTemplate();
            typeof (this.callback) == "function" && this.callback(this.nowPage);
        },
        lastPage: function () {
            this.nowPage = this.totalCount;
            //调用查询数据接口
            this.renderTemplate();
            typeof (this.callback) == "function" && this.callback(this.nowPage);
        },
        goTo: function () {
            //调用查询数据接口
            this.renderTemplate();
            typeof (this.callback) == "function" && this.callback(this.nowPage);
        }
    }
    return result;
}
///数据表格绑定
//实例
//GridControl.Bind(d.Data, ".gridcontrol", {
//     OrderNumber: {
//         cnName: "网店订单号",
//         index: 0
//     },
//     WaresCount: {
//         cnName: "品种数",
//         index: 1
//     },
//     WaresQty: {
//         cnName: "商品数",
//         index: 2
//     }
// });
Controller.GridControl = {
    totalCount: 0,
    actionBack: null,
    //绑定数据源
    Bind: function (d, divname, colSetting, ordinal, checkBtn) {
        var self = this;
        var ordinal = ordinal!=null ? ordinal : false; //显示序号
        var checkBtn = checkBtn!=null ? checkBtn : false; //是否显示勾选

        var conter = typeof (divname) == "string" ? $(divname) : divname;
        //清空原有
        conter.html('');
        var data = null;
        //列排序开始
        var colarr = [];
        for (var obj in colSetting) {
            colSetting[obj]["key"] = obj;
            colSetting[obj]["visible"] = colSetting[obj]["visible"] == false ? colSetting[obj]["visible"] : true;
            colarr.push(colSetting[obj])
        }
        colarr.sort(function (a, b) {
            return (a.index ? a.index : 0) - (b.index ? b.index : 0);
        });
        //列排序结束
        if (d) {
            data = d.List == undefined ? this.EchoEntity(d) : this.EchoEntity(d.List);
            if (d.List) {
                this.totalCount = d.PageCount;
            }
        }
        var $table = $("<div></div>").addClass("shop-table");
        var isTitle = true;
        if (!data || data.length <= 0) {
            //如果数据为空，只打印表头
            if (isTitle) {
                var $title_row = $("<div></div>").addClass("table-tr").addClass("table-title");
                //显示表头
                var $th = $("<div></div>").addClass("table-th");
                //显示勾选
                if (checkBtn == true) {
                    $title_row.append('<div class="table-th table-check"><input type="checkbox" class="shop-table-checkAll"></div>');
                }
                //显示序号
                if (ordinal == true) {
                    $title_row.append('<div class="table-th  table-ordinal">序号</div>');
                }
                for (var i = 0; i < colarr.length; i++) {
                    if (!colarr[i].visible) {
                        continue;
                    }
                    if (colarr[i].width) {
                        var $th = $('<div style="width:' + colarr[i].width + ';"></div>').addClass("table-th");
                    } else {
                        var $th = $('<div></div>').addClass("table-th");
                    }
                    $th.html(colarr[i].cnName);
                    $title_row.append($th);
                }
                $table.append($title_row);
                isTitle = false; //不再打印表头
            }

            conter.append($table);
            return false;
        }
        data.forEach(function (d, di) {
            if (isTitle) {
                var $title_row = $("<div></div>").addClass("table-tr").addClass("table-title");
                if (checkBtn == true) {
                    $title_row.append('<div class="table-th table-check"><input type="checkbox" class="shop-table-checkAll"></div>');
                }
                //显示序号
                if (ordinal == true) {
                    $title_row.append('<div class="table-th  table-ordinal">序号</div>');
                }
                for (var i = 0; i < colarr.length; i++) {
                    if (!colarr[i].visible) {
                        continue;
                    }
                    d.columns.forEach(function (col, index) {
                        var colObj = null;
                        if (colarr[i].key == col.title) {
                            colObj = colarr[i];
                        }
                        if (colObj != null) {
                            if (colarr[i].width) {
                                var $th = $('<div style="width:' + colarr[i].width + ';"></div>').addClass("table-th");
                            } else {
                                var $th = $('<div></div>').addClass("table-th");
                            }
                            $th.html(colObj.cnName);
                            $title_row.append($th);
                        }
                    });
                    $table.append($title_row);
                    isTitle = false; //不再打印表头
                }
            }
            if (typeof d === 'object' && !isNaN(d.length)) {
                var $row = $("<div></div>").addClass("table-group");
                //是数组
                d.forEach(function (row, index) {
                    var $rowgroup = $("<div></div>").addClass("table-tr").addClass("table-body"); 
                    //显示勾选
                    if (!d) return false;
                    var rowobj = {};
                    if (checkBtn == true) {
                        $rowgroup.append('<div class="table-th table-check"><input type="checkbox"></div>');
                    }
                    //显示序号
                    if (ordinal == true && index==0) {
                        $rowgroup.append('<div class="table-th table-ordinal">' + (data.indexOf(d) + 1) + '</div>');
                    }else if(ordinal == true && index>0){
                        $rowgroup.append('<div class="table-th table-ordinal"></div>');
                    }
                    for (var i = 0; i < colarr.length; i++) {
                        row.columns.forEach(function (col, index) {
                            rowobj[col.title] = col.val;
                            if (colarr[i].visible) {
                                var colObj = null;
                                //添加转换器
                                var convert = null;
                                if (colarr[i].key == col.title) {
                                    colObj = colarr[i];
                                }
                                if (colObj != null) {
                                    rowobj[col.title] = col.val;
                                    convert = colObj["converter"];
                                    if (colarr[i].width) {
                                        var $th = $('<div style="width:' + colarr[i].width + ';"></div>').addClass("table-th");
                                    } else {
                                        var $th = $('<div></div>').addClass("table-th");
                                    }
                                    if (convert != null) {
                                        var _html = convert(col.val, rowobj);
                                        $th.html(_html);
                                    } else {
                                        $th.html(col.val == null || col.val == 'null' ? '' : col.val);
                                    }
                                    //$th.html(col.val);
                                    $rowgroup.append($th);
                                }
                            }
                        });
                    }
                    $row.append($rowgroup);
                });
            } else {                
                var $row = $("<div></div>").addClass("table-tr").addClass("table-body"); 
                //显示勾选
                if (!d) return false;
                var rowobj = {};
                if (checkBtn == true) {
                    $row.append('<div class="table-th table-check"><input type="checkbox"></div>');
                }
                //显示序号
                if (ordinal == true) {
                    $row.append('<div class="table-th table-ordinal">' + (data.indexOf(d) + 1) + '</div>');
                }
                for (var i = 0; i < colarr.length; i++) {

                    d.columns.forEach(function (col, index) {
                        rowobj[col.title] = col.val;
                        if (colarr[i].visible) {
                            var colObj = null;
                            //添加转换器
                            var convert = null;
                            if (colarr[i].key == col.title) {
                                colObj = colarr[i];
                            }
                            if (colObj != null) {
                                rowobj[col.title] = col.val;
                                convert = colObj["converter"];
                                if (colarr[i].width) {
                                    var $th = $('<div style="width:' + colarr[i].width + ';"></div>').addClass("table-th");
                                } else {
                                    var $th = $('<div></div>').addClass("table-th");
                                }
                                if (convert != null) {
                                    var _html = convert(col.val, rowobj);
                                    $th.html(_html);
                                } else {
                                    $th.html(col.val == null || col.val == 'null' ? '' : col.val);
                                }
                                //$th.html(col.val);
                                $row.append($th);
                            }
                        }
                    });
                }
            }
            $row.off('click').on('click', function () {
                $(this).addClass("Controller-active").siblings('.table-tr').removeClass("Controller-active");
            });
            $table.append($row);
        });
        conter.append($table);
        $(".Controller-btn-action").off('click').on('click', function () {
            typeof (self.actionBack) == 'function' && self.actionBack($(this));
        });
        //添加事件
        //全选方法
        conter.on("click", ".table-title input[type=checkbox]", function (e) {
            //阻止冒泡
            e.stopPropagation();
            //input
            console.log(1);
            if ($(this).is(":checked")) {
                conter.find(".table-body input[type=checkbox]").prop("checked", true)
                conter.find(".table-body").addClass("shop-selected");
            } else {
                conter.find(".table-body input[type=checkbox]").prop("checked", false);
                conter.find(".table-body").removeClass("shop-selected");
            }
        });
        conter.on("click", ".table-body input[type=checkbox]", function (e) {
            //阻止冒泡
            e.stopPropagation();
            //input
            //多选
            if ($(this).is(":checked")) {
                //选中样式
                $(this).parents(".table-body").addClass("shop-selected");
            } else {
                $(this).parents(".table-body").removeClass("shop-selected");
            }
            if (conter.find(".table-body input[type=checkbox]").not(":checked").length == 0) {
                conter.find(".table-title input[type=checkbox]").prop("checked", true);
            } else {
                conter.find(".table-title input[type=checkbox]").prop("checked", false);
            }
        })
    },
    //将接口返回的Entity对象兑入表格对象中
    EchoEntity: function (data) {
        var iEnumerate = []; //列表对象
        data.forEach(function (d, i) {
            if (typeof d === "object" && !isNaN(d.length)) {
                //是数组，递归回调
                iEnumerate.push(Controller.GridControl.EchoEntity(d));
            } else {
                //是对象就解析
                var obj = new Object();
                obj.columns = []; //所有属性和值
                for (var field in d) {
                    var col = new Object();
                    eval("col.title='" + field + "';");
                    eval("col.val='" + d[field] + "';");
                    obj.columns.push(col);
                }
                iEnumerate.push(obj);
            }
        });
        return iEnumerate;

    }
}
//弹窗
Controller.Alert = function (str, autoHide, delay) {
    //清除原有
    $("body").find(".controller-alert").remove();
    var _html;
    var autoHide = autoHide || true;
    var delay = delay || 3000;
    _html = '<div class="controller-alert" style="position: fixed;width: 600px;line-height: 40px;text-align: center;left:50%;margin-left: -300px;top: 50%;z-index: 55;border-radius: 4px;overflow: hidden;">\
    <div style="background: #000;position: absolute;left: 0px;top: 0px;width: 100%;height: 100%;z-index: 1;opacity: 0.7;filter: alpha(opacity=70);"></div>\
        <span style="position: relative;z-index: 56;color: #fff;">' + str + '</span>\
    </div>';
    $("body").append(_html);
    $(".controller-alert").show(1000);
    if (autoHide) {
        var timer = setTimeout(function () {
            $(".controller-alert").hide(1000);
            $(".controller-alert").remove();
        }, delay);
    } else {
        $("body").not(".controller-alert").click(function (e) {
            $(".controller-alert").hide(1000);
            $(".controller-alert").remove();
        });
    }
}

/*
 *公用js，系统封装的数据绑定方法放在这里
 */
//页面绑定数据源
Data["Fill"] = function (obj, converts) {
    var data = this.ParseData(obj);
    if (!data) {
        return;
    }
    var uiCollection = $('[binding]');
    uiCollection.each(function (val) {
        var cur = $(this);
        cur.html('');
        var keys = cur.attr("binding").split(',');
        var convert = cur.attr("converter");
        var _html = '';
        for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            if (convert) {
                try {
                    var converter = converts[convert];
                    var ret = typeof (converter) == 'function' && converter(data[key], cur);
                    _html += ret;
                } catch (err) {
                    console.error(err);
                }
            } else {
                if (!data[key]) {
                    _html = '';
                    continue;
                } else {
                    _html += data[key];
                }
            }
        }
        cur.html(_html);
    });
};
Data["ParseData"] = function (obj) {
    var result = {};
    var data = null;
    if (obj.result != 0) {
        //服务器抛错
        //alert('服务器内部错误请联系管理员');
        alert(obj.promptMsg);
        return false;
    }
    if (obj.retValue && obj.retValue.List) {
        data = obj.retValue.List;
    } else {
        data = obj.retValue;
    }
    if (!data || data.length < 0) {
        alert('未找到当前数据');
        return null;
    }
    if (data.length > 0) {
        result = data[0];
    } else {
        result = data;
    }
    return result;
};
Data["CollectPara"] = function (conter) {
    var formel = $(conter).find('[name]');
    var result = {};
    formel.each(function (key, val) {
        var cur = $(this);
        var names = cur.attr("name");
        result[names] = cur.val();
    });
    return result;
};
Data["FillForm"] = function (obj, conter) {
    var data = obj;
    var formel = $(conter).find('[name]');
    formel.each(function (key, val) {
        var cur = $(this);
        var names = cur.attr("name");
        cur.val(obj[names]);
    });
}
//扩展window.location方法
QueryParse();

function QueryParse() {
    var result = {};
    var parastr = window.location.href.split('?').length > 1 ? window.location.href.split('?')[1] : '';
    var paragroup = parastr.split("&");
    for (var i = 0; i < paragroup.length; i++) {
        var item = paragroup[i].split('=');
        var key = item[0];
        var val = item[1];
        result[key] = val;
    }
    window.location['query'] = result;
};
//是否存在cookie中用户名和密码，不存在则返回登录页
function existcookie() {
    var username = Cookie.getCookie("username");
    var password = Cookie.getCookie("password");
    if (username == "" || password == "") {
        window.location.href = "login.html";
    }
}
//设置cookie
Cookie.setCookie = function (c_name, value, expiredays, pathstr) {
    var exdate = new Date();
    var pathstr = !pathstr || pathstr == "" ? "/" : pathstr;
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
        ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) + "; path=" + pathstr;
}

//获取cookie
Cookie.getCookie = function getCookie(c_name) {
    if (document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            var c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return ""
}
///检查cookie
Cookie.checkCookie = function checkCookie() {
    var username = Cookie.getCookie('username');
    if (username != null && username != "")
        return 0;
    else {
        if (username != null && username != "") {
            Cookie.setCookie('username', username, 365);
        }
    }
    return 1;
}
///删除cookie
Cookie.deleteCookie = function (name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = Cookie.getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}
//页面加载，动态提示
Controller.Loader = {
    //loader初始化
    init: function (obj) {
        var param = {
            target: null,
            width: 50,
            height: 50
        };
        //清空上一次添加，避免重复
        Controller.Loader.stop();
        //拿到父级，如果没有，默认插入到body中
        var cur = typeof (param.target) == "string" ? ($(param.target) ? $(param.target) : $("body")) : (param.target ? param.target : $("body"));
        var _html = '<div id="shop-loader" style="position: fixed;width: ' + (param.width + 40) + 'px;height:' + (param.height + 40) + 'px;text-align: center;left:50%;margin-left: -' + (param.width / 2 + 20) + 'px;top: 50%;margin-top:-' + (param.height / 2 + 20) + 'px;z-index: 55;border-radius: 4px;overflow: hidden;">\
        <div style="background: #000;position: absolute;left: 0px;top: 0px;width: 100%;height: 100%;z-index: 1;opacity: 0.7;filter: alpha(opacity=70);"></div>\
            <img width="' + param.width + '" height="' + param.height + '" src="' + imgRoot + '/static/loadingSvg/spinning-circles.svg" style="z-index:999;position:relative;top: 20px;" />\
        </div>';
        cur.append(_html);
        Controller.extend();
    },
    stop: function () {
        $("#shop-loader") && $("#shop-loader").remove();
    }
}
/*
 *带token
 *ajax请求
 */
Controller.Ajax = function (param) {
    var para = param;
    //验证token
    //取token；
    var token = Cookie.getCookie("shopToken");
    var send = function (obj) {
        $.ajax(obj);
    };
    if (!token || token.trim() == "") {
        //没有token进行请求
        $.ajax({
            //url:"http://localhost:8003/connect/token",
            url: router + "/connect/token",
            type: "POST",
            data: {
                grant_type: "client_credentials",
                scopes: "verticalsite_api",
                client_id: "verticalsite",
                client_secret: "p@ssw0rd"
            },
            dataType: "json",
            success: function (data) {
                var exdate = new Date();
                exdate = new Date(exdate.setHours(exdate.getHours() + 2));
                document.cookie = "shopToken=" + escape(data.access_token) + ";expires=" + exdate.toGMTString();
                token = Cookie.getCookie("shopToken");
                if (param.headers) {
                    param.headers["Authorization"] = "Bearer " + token;
                } else {
                    param["headers"] = {
                        Authorization: "Bearer " + token
                    };
                }
                send(param);
            }
        });
    } else {
        if (param.headers) {
            param.headers["Authorization"] = "Bearer " + token;
        } else {
            param["headers"] = {
                Authorization: "Bearer " + token
            };
        }
        send(param);
    }
};
// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;

}

//弹窗信息
//信息提示封装
// 李闯

//显示提示信息
//调用方法
//Message.Show("标题","提示信息",确定按钮回调函数,取消按钮回调函数,按钮类型现在不用传); 
Message.Show = function (title, msg, type, autoHide, delay, buttonType, saveFun, closeFun) {
    //清空
    Message.Close();
    if (timer) {
        clearInterval(timer);
    }
    var delay = delay ? delay : 5;
    var _html = '<div id="shop-message-mask" style="position: fixed;left: 0px;right: 0px;top: 0px;bottom: 0px;z-index: 99;background: url(' + imgRootDeep + '/static/shop_mask_bg5.png) repeat;">\
                    <div style="padding: 5px;width: 480px;height: 225px;position: absolute;left: 50%;top: 50%;margin-left: -242px;margin-top: -115px;background: url(' + imgRootDeep + '/static/shop_message_border.png) repeat;">\
                        <div style="background: #fff;position: absolute;left: 5px;top: 5px;bottom: 5px;right: 5px;">\
                            <div style="height: 40px;width: 100%;background: #f5f5f5;line-height: 40px;">\
                                <span style="margin-left: 15px;font-size: 14px;color: #333;">' + title + '</span>\
                                <div id="shop-message-close" style="float: right;margin-top: 15px;margin-right: 12px;font-size: 12px;line-height: 12px;height: 10px;width: 10px;text-align: center;cursor: pointer;color: #7a7a7a;  ">X</div>\
                            </div>\
                            <div class="shop-message-mask-html" style="margin: 41px 15px 0px 15px;overflow: hidden; height: 42px;white-space: nowrap;word-break: keep-all;line-height: 40px;text-align: center;">';
    if (type && type == "right") {
        _html += '<img src="' + imgRootDeep + '/static/shop_tip_right.png" style="display: inline; vertical-align: middle;margin-right: 10px;" width="40" height="40">';
    } else {
        _html += '<img src="' + imgRootDeep + '/static/shop_tip_warning.png" style="display: inline; vertical-align: middle;margin-right: 10px;" width="40" height="40">';
    }
    _html += '<span style="vertical-align: middle;color: #666;font-size: 14px;">' + msg + '</span>\
                            </div>';
    //自动隐藏
    if (autoHide) {
        _html += '<span style="margin-left: 242px;color: #666;font-size: 12px;"><span id="shop-auto-time">' + delay + '</span>s后自动关闭<span></span></span>';
    }
    _html += '<div style="margin: 42px 15px 0px; text-align: center;height: 30px;overflow: hidden;">';
    if (buttonType && buttonType == "sure") {
        _html += '<div id="shop-message-save" style="cursor: pointer;width: 64px;height: 30px;display: inline-block;color: #fff;line-height: 30px;font-size: 12px;text-align: center;background: #e64545;border-radius: 3px;">确定</div>';
    } else {
        _html += '<div id="shop-message-save" style="cursor: pointer;width: 64px;height: 30px;display: inline-block;color: #fff;line-height: 30px;font-size: 12px;text-align: center;background: #e64545;border-radius: 3px;margin-right: 10px;">确定</div>\
        <div id="shop-message-cancle" style="cursor: pointer;width: 64px;height: 30px;display: inline-block;color: #333;line-height: 30px;font-size: 12px;text-align: center;background: #eee;border-radius: 3px;">取消</div>';

    }
    _html += '</div>\
                                </div>`\
                                    </div>\
                                </div>`';
    //显示
    $("body").append(_html);
    //添加事件监听
    //查号关闭弹窗
    $("#shop-message-mask #shop-message-close").off("click").on("click", function (e) {
        Message.Close();
    });
    if (autoHide) {
        var timer = setInterval(function () {
            if (delay == 0) {
                clearInterval(timer);
                Message.Close();
                return;
            }
            $("#shop-message-mask #shop-auto-time").text(delay);
            delay--;
        }, 1000);
    }
    //保存按钮
    $("#shop-message-mask #shop-message-save").off("click").on("click", function (e) {
        var result = true;
        result = saveFun && typeof (saveFun) == "function" && saveFun(); //有回调函数，先执行回调。
        if (result) {
            //执行关闭操作
            clearInterval(timer);
            Message.Close();
        }
    });
    //关闭按钮
    $("#shop-message-mask #shop-message-cancle").off("click").on("click", function (e) {
        var result = true;
        result = closeFun && typeof (closeFun) == "function" && closeFun(); //有回调函数，先执行回调。
        if (result) {
            //执行关闭操作
            clearInterval(timer);
            Message.Close();
        }
    });
    return this;
};
//设置内容
Message.setHtml = function (_html) {
    if ($("#shop-message-mask")) {
        $("#shop-message-mask").find(".shop-message-mask-html").html(_html);
    }
}
//关闭消息提示框
Message.Close = function () {
    if ($("#shop-message-mask")) {
        $("#shop-message-mask").remove();
    }
}
//取数据中的数字
Controller.getNum = function (str) {
    var _str = "0";
    try {
        _str = str.replace(/[^0-9]/ig, "");
    } catch (e) {
        console.warn("检查数据类型");
    }
    return _str;
}
//选择框下拉控件。
Controller.DateSelect = function (obj) {
    var result = {
        content: null, //容器
        list: null, //候选项对象数组{name:"",value:""}
        event: "click", //显示事件，目前只有hover或者click
        selected: "undefine", //选中
        callback: null //选中的回调
    };
    //初始化方法
    result.init = function (obj) {
        Controller.extend(result, obj);
        //渲染模板
        result.renderTemplate();
        //监听事件
        result.addEvent();
    };
    result.renderTemplate = function () {
        var _html = '';
        _html += '<div class="shop-date-selector-con"><div id="shop-date-selector">';
        //内容
        if (this.list && this.list.length > 0) {
            _html += '<div class="shop-date-selected" value="' + this.list[0].value + '">' + this.list[0].name + '</div>\
                    <div class="shop-clear"></div>';
            this.selected = this.list[0].value;
            _html += '<ul>';
            for (var i = 0; i < this.list.length; i++) {
                _html += '<li data-value="' + this.list[i].value + '">' + this.list[i].name + '</li>';
            }
            _html += '</ul>';
        } else {
            console.warn("未绑定数据集");
        }
        _html += '</div></div>';
        //加入容器
        var conter = this.content && typeof (this.content) == "string" ? $(this.content) : this.content;
        //清空
        conter.html("");
        //载入
        conter.append(_html);
    };
    //添加事件监听
    result.addEvent = function () {
        switch (this.event) {
            case "click":
                //已选项点击
                $("#shop-date-selector").on("click", ".shop-date-selected", function (e) {
                    $(this).parent("#shop-date-selector").toggleClass("shop-active");
                });
                break;
            case "hover":
                $("#shop-date-selector").on("mouseover", function (e) {
                    $(this).addClass("shop-active");
                });
                $("#shop-date-selector").on("mouseout", function (e) {
                    $(this).removeClass("shop-active");
                });
                break;
        }

        //候选项点击
        $("#shop-date-selector").on("click", "ul li", function (e) {
            //取到对应的值，
            var _val = $(this).attr("data-value");
            var name = $(this).text();
            //设置选择项
            result.selected = _val;
            //执行回调
            typeof (result.callback) == "function" && result.callback(result.selected);
            $(this).parents("#shop-date-selector").find(".shop-date-selected").text(name);
            $(this).parents("#shop-date-selector").find(".shop-date-selected").attr("value", _val);
            $(this).parents("#shop-date-selector").removeClass("shop-active");
        });
    };
    result.init(obj);
    return result;
}